package com.aia.prm.servlet;

import java.lang.reflect.Proxy;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.aia.prm.BeanFactory;
import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.AbstractApplicationServlet;

@SuppressWarnings("serial")
public class SpringApplicatioinServlet extends AbstractApplicationServlet {
	private static final Logger logger = Logger.getLogger(SpringApplicatioinServlet.class);
	// Private fields
	private String applicationClassName;
	// Private fields
	private Class<? extends Application> applicationClass;

	@SuppressWarnings("unchecked")
	@Override
	public void init(javax.servlet.ServletConfig servletConfig) throws javax.servlet.ServletException {
		super.init(servletConfig);
		applicationClassName = servletConfig.getInitParameter("application");
		if (applicationClassName == null) {
			String msg = "Application not specified in servlet parameters";
			logger.fatal(msg);
			throw new ServletException(msg);
		}
		
		try {
			applicationClass = (Class<? extends Application>) BeanFactory.get().getType(applicationClassName);
		} catch (Exception e) {
			String msg = "Can not get Class";
			logger.fatal(msg, e);
			throw new ServletException(msg, e);
		}
		
		if(Proxy.isProxyClass(applicationClass)){
			String msg = "Can not use proxy for the application";
			logger.fatal(msg);
			throw new ServletException(msg);
		}
	}

	@Override
	protected Application getNewApplication(HttpServletRequest request) throws ServletException {
		Application application = null;
		try {
			application = (Application) BeanFactory.get().getBean(applicationClassName);
		} catch (Exception e) {
			logger.fatal(e);
			throw new RuntimeException(e);
		}
		return application;
	}

	@Override
	protected Class<? extends Application> getApplicationClass() throws ClassNotFoundException {
		return applicationClass;
	}
}
